import time
import datetime
import typing
import calendar


def timeStamp(timeNum):
    """时间戳毫秒级转时间"""
    time_stamp = float(timeNum / 1000)
    time_array = time.localtime(time_stamp)
    other_Time = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
    return other_Time


def timeStampToDateTime(timeNum):
    """时间戳毫秒级转时间"""
    return datetime.datetime.strptime(timeStamp(timeNum), '%Y-%m-%d %H:%M:%S')


def datetime_to_time_stamp(date) -> int:
    """ 日期转时间戳 毫秒级"""
    return int(time.mktime(time.strptime(date, "%Y-%m-%d %H:%M:%S")) * 1000)


def datetime_obj_to_time_stamp(dateTime: datetime.datetime) -> int:
    """
     int(time.mktime(now.timetuple()))
    日期转时间戳 毫秒级
    """
    return int(time.mktime(dateTime.timetuple()) * 1000)


def get_date_range(date_type: int, add=0) -> typing.Tuple[datetime.datetime, datetime.datetime]:
    """获取当天，月，年"""
    now = datetime.datetime.now()
    if date_type == 1:
        now += datetime.timedelta(days=add)
        # 获取今天零点
        zeroToday = now - datetime.timedelta(hours=now.hour, minutes=now.minute, seconds=now.second,
                                             microseconds=now.microsecond)
        # 获取23:59:59
        lastToday = zeroToday + datetime.timedelta(hours=23, minutes=59, seconds=59)
        return zeroToday, lastToday
    elif date_type == 2:
        month = now.month + add if (now.month + add) > 0 else 12 + (now.month + add)
        year = now.year if month >= 1 else now.year - 1
        this_month_start = datetime.datetime(year, month, 1)
        this_month_end = datetime.datetime(year, month, calendar.monthrange(year, month)[1])
        this_month_end += datetime.timedelta(hours=23, minutes=59, seconds=59)
        return this_month_start, this_month_end
    elif date_type == 3:
        year = now.year + add
        last_quarter_start = datetime.datetime(year, 1, 1)
        last_quarter_end = datetime.datetime(year, 12, 31)
        return last_quarter_start, last_quarter_end


def gen_fromtime_endtime(day=0) -> tuple[int, int]:
    """起始时间戳转换
    Args:
        day (int, optional): 0: 今天， -1: 昨天. Defaults to 0.

    Returns:
        tuple: start_timestamp, end_timestamp
    """
    date = datetime.date.today() + datetime.timedelta(day)
    end_date = date + datetime.timedelta(1)
    from_time = int(datetime.datetime(year=date.year, month=date.month, day=date.day).timestamp() * 1000)
    end_time = int(datetime.datetime(year=end_date.year, month=end_date.month, day=end_date.day).timestamp() * 1000) - 1
    return from_time, end_time
